﻿#region Copyright (c) 2012-10, Olaf Kober <amarok.projects@gmail.com>
//================================================================================
//	Permission is hereby granted, free of charge, to any person obtaining a copy
//	of this software and associated documentation files (the "Software"), to deal
//	in the Software without restriction, including without limitation the rights
//	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//	copies of the Software, and to permit persons to whom the Software is
//	furnished to do so, subject to the following conditions:
//
//	The above copyright notice and this permission notice shall be included in
//	all copies or substantial portions of the Software.
//
//	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//	THE SOFTWARE.
//================================================================================
#endregion

using System;
using System.IO;


namespace Amarok
{
	/// <summary>
	/// This type provides extension methods for <see cref="System.IO.Stream"/>.
	/// </summary>
	public static class StreamExtensions
	{
		#region ++ Public Interface (Write) ++

		/// <summary>
		/// Writes the supplied buffer segment to the stream.
		/// </summary>
		/// 
		/// <param name="stream">
		/// The stream to write to.</param>
		/// <param name="data">
		/// The buffer segment containing the sequence of bytes to write.</param>
		public static void Write(this Stream stream, BufferSegment data)
		{
			stream.Write(data.Buffer, data.Offset, data.Count);
		}

		#endregion

		#region ++ Public Static Interface (ReadToEnd) ++

		/// <summary>
		/// Reads all data from the given stream into a new buffer segment.
		/// </summary>
		/// 
		/// <param name="stream">
		/// The stream to read from.</param>
		/// <returns>
		/// The buffer segment containing the sequence of bytes read from the stream.</returns>
		/// 
		/// <exception cref="NotSupportedException">
		/// A class derived from Stream does not support seeking.</exception>
		/// <exception cref="ObjectDisposedException">
		/// Methods were called after the stream was closed.</exception>
		public static BufferSegment ReadToEnd(this Stream stream)
		{
			if (stream.Length == 0)
			{
				return BufferSegment.Empty;
			}
			else
			{
				var data = new Byte[stream.Length];
				stream.Read(data, 0, data.Length);
				return new BufferSegment(data);
			}
		}

		#endregion

	}
}
